/*
2021-10-26 
https://leetcode-cn.com/problems/number-of-valid-words-in-a-sentence/
*/
class Solution {
public:
    int countValidWords(string sentence) {
        int res=0;
        int cnt1=0;
        int cnt2=0;
        int len=0;
        string str="";
        int n=sentence.length(),ans=0;
        while(n-1>=0&&sentence[n-1]==' ')
            n--;
        sentence=sentence.substr(0,n);
        bool num=false;
        for(auto t:sentence)
        {
            if(t==' ')
            {
                if(len>=1 && !num && cnt1<=1 && cnt2<=1 && str[0]!='-' && str[len-1]!='-')
                {
                    if(cnt2==1 && (str[len-1]=='!' || str[len-1]=='.' || str[len-1]==',')) 
                    {
                        if(len>=2 && str[len-2]!='-') res++;
                        else if(len<2) res++;
                    }
                    else if(cnt2==0) res++;
                }
                //cout<<str[0]<<' '<<str[len-1]<<endl;
                cnt1=0,cnt2=0;
                len=0;
                num=false;
                str="";
            }
            else 
            {
                str+=t;
                if(t=='-') cnt1++;
                if(t=='!' || t=='.' || t==',') cnt2++;
                if(t>='0' && t<='9') num=true;
                len++;
            }
        }
        //cout<<str<<endl;
        if(len>=1 && !num && cnt1<=1 && cnt2<=1 && str[0]!='-' && str[len-1]!='-')
                {
                    if(cnt2==1 && (str[len-1]=='!' || str[len-1]=='.' || str[len-1]==',')) 
                    {
                        if(len>=2 && str[len-2]!='-') res++;
                        else if(len<2) res++;
                    }
                    else if(cnt2==0) res++;
                }

        return res;
    }
};
